package me.caofeng.controller;

import com.sun.org.apache.regexp.internal.RE;
import me.caofeng.annotation.Authentication;
import me.caofeng.enums.ResponseCode;
import me.caofeng.enums.Role;
import me.caofeng.pojo.*;
import me.caofeng.service.api.IUserService;
import me.caofeng.util.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.controller
 * @Description:
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-16 10:30
 * @Version: V1.0
 */
@RequestMapping(value = "user")
@Controller
public class UserController {
    private static Logger LOGGER = LogManager.getLogger(UserController.class);

    @Autowired
    private IUserService userService;


    @RequestMapping(value = "register", method = RequestMethod.POST)
    @ResponseBody
    public Response<User> register(@Valid User user ,BindingResult bindingResult,HttpSession session) {
        if (bindingResult.hasFieldErrors("phone")){
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT,"请输入正确的手机号",null);
        }

        if (bindingResult.hasFieldErrors("password")){
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT,
                    "请输入6为以上数字或字码密码",null);
        }

        if (bindingResult.hasFieldErrors("name")){
           return Response.response(ResponseCode.ILLEGAL_ARGUMENT,"请输入2位以上用户名",null);
        }

        Response<User> response = userService.register(user);

        if (response.isSuccess()) {
            session.setAttribute(Constant.USER, response.getData());
        }

        return response;
    }

    @RequestMapping(value = "register", method = RequestMethod.GET)
    public String toRegister() {
        return "register";
    }

    @RequestMapping(value = "register/{phone}", method = RequestMethod.GET)
    @ResponseBody
    public Response isRegister(@PathVariable("phone") String phone) {
        return userService.isRegister(phone);
    }


    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String toLogin() {
        return "login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public Response<User> login(@Valid User user, BindingResult bindingResult,HttpSession session) {
        if (bindingResult.hasFieldErrors("phone")){
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT,
                    "请输入正确的手机号", null);
        }

        if (bindingResult.hasFieldErrors("password")){
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT,
                    "密码不正确", null);
        }

        Response<User> response = userService.login(user.getPhone(),user.getPassword());

        if (response.isSuccess()) {
            session.setAttribute(Constant.USER, response.getData());
        }

        return response;
    }


    @RequestMapping(value = "info", method = RequestMethod.GET)
    @ResponseBody
    @Authentication(role = Role.MEMBER)
    public Response<User> getUserInfo(HttpSession session) {
        User user = (User) session.getAttribute(Constant.USER);
        return userService.getUserInfo(user.getUid());
    }

    @RequestMapping(value = "name", method = RequestMethod.PUT)
    @Authentication
    @ResponseBody
    public Response<User> updateUserName(@RequestBody @Valid User request,
                                         BindingResult bindingResult,
                                         HttpSession session) {
        User user = (User) session.getAttribute(Constant.USER);

        if (bindingResult.hasFieldErrors("name")){
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT,"用户名需要2位以上",null);
        }

        Response response = userService.updateUserName(user, request.getName());
        if (response.isSuccess()) {
            user.setName(request.getName());
            session.setAttribute("user", user);
        }
        return response;
    }

    //修改密码
    @RequestMapping(value = "password", method = RequestMethod.PUT)
    @Authentication
    @ResponseBody
    public Response updatePassword(@RequestBody @Valid User request,
                                   BindingResult bindingResult,
                                   HttpSession session) {
        User user = (User) session.getAttribute(Constant.USER);

        if (bindingResult.hasFieldErrors("password")){
            return  Response.response(ResponseCode.ILLEGAL_ARGUMENT,
                    "密码需要6位以上",null);
        }

        Response response = userService.updatePassword(request.getPassword(), user.getUid());

        if (response.isSuccess()) {
            session.invalidate();
        }

        return response;
    }

    /**
     * @param token 验证完短信验证码后，服务器返回的data,可以放在url中或者表单中
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/6/19 15:06
     * @Description: 重置登录密码
     */
    @RequestMapping(value = "password", method = RequestMethod.POST)
    @ResponseBody
    public Response resetPassword(@RequestParam("password") String password,
                                  @RequestParam("confirm") String confirm,
                                  @RequestParam("token") String token,
                                  HttpSession session) {
        Response response = userService.resetPassword(password, confirm, token);
        if (response.isSuccess()) {
            session.invalidate();
        }
        return response;
    }

    @RequestMapping(value = "phone", method = RequestMethod.PUT)
    @Authentication
    @ResponseBody
    public Response updatePhone(@RequestBody @Valid SmsCode code,
                                BindingResult bindingResult,
                                HttpSession session) {

        if (bindingResult.hasFieldErrors()){
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT,"请输入正确的验证码",null);
        }

        User user = (User) session.getAttribute("user");

        Response response = userService.updatePhone(code,user.getUid());

        if (response.isSuccess()) {
            user.setPhone(code.getPhone());
            session.setAttribute(Constant.USER,user);
        }

        return  response;
    }


    @RequestMapping(value = "questions", method = RequestMethod.POST)
    @Authentication
    @ResponseBody
    public Response addSecurityQuestions(@Valid QuestionForm questions,
                                         BindingResult result,
                                         HttpSession session) {
        LOGGER.info(result.getAllErrors());
        if (result.hasFieldErrors()){
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT,"请输入问题或答案",null);
        }

        User user = (User) session.getAttribute("user");
        return userService.addSecurityQuestions(questions, user.getUid());
    }

    @RequestMapping(value = "questions", method = RequestMethod.GET)
    @ResponseBody
    @Authentication
    public Response<List<SecurityQuestion>> getSecurityQuestions(HttpSession session) {
        User user = (User) session.getAttribute("user");
        return userService.getSecurityQuestions(user.getUid());
    }

    @RequestMapping(value = "question/{id}", method = RequestMethod.GET)
    @Authentication
    @ResponseBody
    public Response<SecurityQuestion> getSecurityQuestion(@PathVariable("id") Integer id,
                                                          HttpSession session) {
        User user = (User) session.getAttribute("user");
        return userService.getSecurityQuestion(id, user.getUid());
    }

    @RequestMapping(value = "question/{id}", method = RequestMethod.PUT)
    @Authentication
    @ResponseBody
    public Response<SecurityQuestion> updateSecurityQuestion(@PathVariable("id") Integer id,
                                                             @RequestBody SecurityQuestion question,
                                                             HttpSession session) {
        User user = (User) session.getAttribute("user");
        LOGGER.debug(question);
        return userService.updateSecurityQuestion(id, question, user.getUid());
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @ResponseBody
    public Response logout(HttpSession session) {
        session.invalidate();
        return Response.response(ResponseCode.SUCCESS, "退出成功", null);
    }

    /**
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/6/19 16:11
     * @Description: 获取用户的安全问题
     */
    @RequestMapping(value = "/{phone}/question", method = RequestMethod.GET)
    @ResponseBody
    public Response<List<SecurityQuestion>> getQuestions(@PathVariable("phone") String phone) {
        return userService.getQuestion(phone);
    }


    @RequestMapping(value = "/{phone}/question/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Response<String> verifyQuestion(@RequestParam("answer") String answer,
                                           @PathVariable("phone") String phone,
                                           @PathVariable("id") Integer id) {
        return userService.verifyQuestion(answer,phone,id);
    }


}
